﻿@page "/modules"

@using Gurux.DLMS.AMI.Shared.DIs
@using Gurux.DLMS.AMI.Shared.DTOs.Enums

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Microsoft.AspNetCore.SignalR.Client
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Module
@using System.Text.Json

@namespace Gurux.DLMS.AMI.Client.Pages.Module

@attribute [Authorize(Roles = GXRoles.Admin)]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier Notifier
@inject GXModuleService modules
@implements IDisposable
@implements IAmiComponent

@if (Title)
{
    <h1>@Properties.Resources.ModulesTitle</h1>
}

@if (_settings != null)
{
    <EditForm Model="@_settings">
        <div class="row">
            <div style="width:100%">
                <div class="form-group">
                    @if (_settings?.Checked != null)
                    {
                        <label>@string.Format(Properties.Resources.LastChecked, ClientHelpers.GetLastChecked(_settings?.Checked))</label>
                    }
                    <button type="button" class="btn btn-link" @onclick="OnCheck">(@Properties.Resources.CheckManually)</button>
                </div>
            </div>
        </div>
    </EditForm>
}
<GXTable @ref="table"
         Context="module"
         ItemsProvider="@GetItems"
         SelectionMode="SelectionMode.Single"
         Filter="@Filter"
         Columns="@Columns"
         CanEdit="@CanEdit"
         ShowRemoved="false"
         ShowAllUsers="false"
         OnSearch="@Updated">
    <FilterContent>
        <th>
            <input class="form-control" type="text" placeholder="@Properties.Resources.FilterByName"
                   @onchange="@((ChangeEventArgs __e) => filter.Id = Convert.ToString(__e.Value))" />
        </th>
        <th>
            <input class="form-control" type="text" placeholder="Filter by version..."
                   @onchange="@((ChangeEventArgs __e) => filter.Version = Convert.ToString(__e.Value))" />
        </th>
        <th>
            <input class="form-control" placeholder="按创建时间..."
                   type="datetime-local"
                   @onchange="@((ChangeEventArgs __e) => filter.CreationTime = Convert.ToDateTime(__e.Value))" />
        </th>
        <th>
            <input class="form-control" placeholder="Filter by updated time..."
                   type="datetime-local"
                   @onchange="@((ChangeEventArgs __e) => filter.Updated = Convert.ToDateTime(__e.Value))" />
        </th>
    </FilterContent>
    <MenuContent>
        <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.AgentGroupManager)>
            <ContextMenuItem Text="@Properties.Resources.Edit" Icon="oi oi-pencil" OnClick="@OnEdit"></ContextMenuItem>
            <ContextMenuItem Text="@Properties.Resources.Remove" Icon="oi oi-trash" OnClick="@OnRemove"></ContextMenuItem>
        </AuthorizeView>
    </MenuContent>
    <HeaderContent>
        <th>@Properties.Resources.Name</th>
        <th>@Properties.Resources.Version</th>
        <Th Id="CreationTime" SortMode="SortMode.Descending">@Properties.Resources.CreationTime</Th>
            <th>@Properties.Resources.Updated</th>
    </HeaderContent>
    <ItemContent>
        <Td Link="@("Config/Module/Edit/" + module.Id)">
            <span class=@(ClientHelpers.GetActiveDot(module.Active))>
            </span><span class="@module.Icon" aria-hidden="true"></span>@module.Id
        </Td>
        <td>@module.Version</td>
        <td>@module.CreationTime</td>
        <td>@module.Updated</td>
    </ItemContent>
</GXTable>
<Confirm @ref="DeleteConfirmation"
         ConfirmationChanged="OnDeleteConfirmation"
         OkTitle="@Properties.Resources.Remove"
         ConfirmationMessage=""
         AllowDelete="false"
         ConfirmationTitle="@Properties.Resources.AreYouSureYouWantToDeleteSelectedItems">
</Confirm>
<br />
@code {
    [Parameter]
    public Gurux.DLMS.AMI.Client.Pages.Module.ModuleManage? Parent { get; set; }

    /// <summary>
    /// Selected module ID.
    /// </summary>
    [Parameter]
    public string? Id { get; set; }

    /// <inheritdoc />
    public string Name
    {
        get
        {
            return Gurux.DLMS.AMI.Client.Properties.Resources.ModulesTitle;
        }
    }

    /// <inheritdoc />
    public Type? ConfigurationUI
    {
        get
        {
            return null;
        }
    }

    /// <inheritdoc />
    public string? Icon
    {
        get
        {
            return "oi oi-puzzle-piece";
        }
    }

    /// <summary>
    /// Amount of the modules shown on the view.
    /// </summary>
    [Parameter]
    public int Count { get; set; } = 0;

    /// <summary>
    /// Is filter shown.
    /// </summary>
    [Parameter]
    public bool Filter { get; set; } = true;

    /// <summary>
    /// Is header shown.
    /// </summary>
    [Parameter]
    public bool Header { get; set; } = true;

    /// <summary>
    /// Is edit allowed.
    /// </summary>
    [Parameter]
    public bool CanEdit { get; set; } = true;

    /// <summary>
    /// Available columns.
    /// </summary>
    [Parameter]
    public string[]? Columns { get; set; }

    /// <summary>
    /// Is title shown.
    /// </summary>
    [Parameter]
    public bool Title { get; set; } = true;

    /// <summary>
    /// Module filter. Show only installed modules.
    /// </summary>
    private GXModule filter = new GXModule()
        {
            Active = null,
            Status = (ModuleStatus.Installed | ModuleStatus.CustomBuild)
        };

    /// <summary>
    /// User is verified before module is removed.
    /// </summary>
    protected ConfirmBase? DeleteConfirmation;

    /// <summary>
    /// Table reference.
    /// </summary>
    protected GXTable<GXModule>? table;

    /// <summary>
    /// Module settings.
    /// </summary>
    private ModuleSettings? _settings;

    /// <summary>
    /// Update table.
    /// </summary>
    protected async Task Updated()
    {
        try
        {
            if (table != null)
            {
                Notifier?.ClearStatus();
                await table.RefreshDataAsync(true);
            }
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    protected override void OnInitialized()
    {
        try
        {
            if (Notifier == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidNotifier);
            }
            Notifier.ClearStatus();
            Notifier.On<IEnumerable<GXConfiguration>>(this, nameof(IGXHubEvents.ConfigurationSave), (configurations) =>
           {
               try
               {
                   if (configurations != null)
                   {
                       foreach (var it in configurations)
                       {
                           if (it.Name == GXConfigurations.Modules && !string.IsNullOrEmpty(it.Settings))
                           {
                               _settings = JsonSerializer.Deserialize<ModuleSettings>(it.Settings);
                               StateHasChanged();
                               break;
                           }
                       }
                   }
               }
               catch (Exception ex)
               {
                   Notifier?.ProcessError(ex);
               }
           });
            Notifier.On<IEnumerable<GXModule>>(this, nameof(IGXHubEvents.ModuleUpdate), async (modules) =>
            {
                await Updated();
            });
            Notifier.On<IEnumerable<GXModule>>(this, nameof(IGXHubEvents.ModuleDelete), async (modules) =>
            {
                await Updated();
            });
            Notifier.Clear();
            Notifier.UpdateButtons();
            if (table != null && Id != null)
            {
                //Get last selected item.
                table.Active = new GXModule() { Id = Id };
            }
            //Get configuration data.
            if (!string.IsNullOrEmpty(Parent?.Parent?.Active?.Settings))
            {
                _settings = JsonSerializer.Deserialize<ModuleSettings>(Parent.Parent.Active.Settings);
            }
            else
            {
                _settings = new ModuleSettings();
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    private async ValueTask<ItemsProviderResult<GXModule>> GetItems(GXItemsProviderRequest request)
    {
        //Don't clear status or error is lost.
        Notifier?.ProgressStart();
        try
        {
            ListModules req = new ListModules()
                {
                    Index = request.StartIndex,
                    Count = request.Count,
                    Filter = filter,
                    OrderBy = request.OrderBy,
                    Descending = request.Descending,
                    AllUsers = request.ShowAllUserData
                };
            if (Count != 0)
            {
                req.Count = Count;
            }
            var ret = await Http.PostAsJson<ListModulesResponse>("api/Module/List", req, request.CancellationToken);
            return new ItemsProviderResult<GXModule>(ret.Modules, ret.Count);
        }
        catch (TaskCanceledException)
        {
            //Let the table component handle this.
            throw;
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
        return default;
    }

    /// <summary>
    /// Edit module.
    /// </summary>
    public void OnEdit()
    {
        try
        {
            Notifier.ClearStatus();
            if (table?.Active == null)
            {
                throw new Exception(Gurux.DLMS.AMI.Client.Properties.Resources.NoItemIsSelected);
            }
            ClientHelpers.NavigateTo(NavigationManager, Notifier, "/Config/Module/Edit/" + table?.Active.Id);
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }


    /// <summary>
    /// Remove selected module.
    /// </summary>
    public void OnRemove()
    {
        try
        {
            if (table == null || !table.SingleOrDefault().Any())
            {
                throw new Exception(Gurux.DLMS.AMI.Client.Properties.Resources.NoItemIsSelected);
            }
            DeleteConfirmation?.Show(table?.SingleOrDefault()?.Select(s => s.Id).ToArray());
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    /// <summary>
    /// Delete the selected modules groups.
    /// </summary>
    public async Task OnDeleteConfirmation(ConfirmArgs args)
    {
        try
        {
            if (table != null && args.Confirm)
            {
                RemoveModule req = new RemoveModule()
                    {
                        Modules = table.SingleOrDefault().Select(w => w.Id).ToArray()
                    };
                await Http.PostAsJson<RemoveWorkflowGroupResponse>("api/Module/Delete", req);
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    /// <summary>
    /// Check module versions manually.
    /// </summary>
    public async void OnCheck()
    {
        Notifier?.ProgressStart();
        Notifier?.ClearStatus();
        try
        {
            CheckManufacturer req = new CheckManufacturer();
            await Http.PostAsJson<CheckManufacturerResponse>("api/Module/Check", req);
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    public void Dispose()
    {
        Notifier.RemoveListener(this);
    }
}
